<!--
 * @Description: 摄像头拍照配置
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="40"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
        @sort-change="changeTableSort"
      >
        <el-table-column type="selection" width="55" :selectable="row => { return !row.indflag }" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="collectName" label="采集名称" />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.collectSettingNo" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="handleEdit(scope.row)">查看详情</el-button>
            <el-button v-if="judgePermission(40,'delete')" class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="'添加'+'摄像头拍照配置'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="采集名称:" prop="batchNo" class="w50p">
            <el-input v-model="formData.collectName" :disabled="!canInput" />
          </el-form-item>
          <el-form-item label="采集设施:" prop="batchName" class="w50p">
            <el-select v-model="formData.facilityNo" filterable :placeholder="formData.facilityName" :disabled="!canInput" @change="selectfac">
              <el-option
                v-for="(item,index) in facilityList"
                :key="index"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集摄像头:" prop="batchName" class="w50p">
            <el-select v-model="cameramessage" :placeholder="formData.cameraName" :disabled="!canInput">
              <el-option
                v-for="(item,index) in cameraList"
                :key="index"
                :label="item.cameraName"
                :value="{value:item.cameraId,name:item.cameraName} "
              />
            </el-select>
          </el-form-item>
          <el-form-item label="执行选择:" prop="completionDate" class="w50p">
            <el-select v-model="formData.once" :disabled="!canInput">
              <el-option
                v-for="(item,index) in onceList"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集频率:" prop="completionDate" class="w100p">
            <div v-for="(item,index) in datelist" :key="index">
              <el-time-picker
                v-model="item.date"
                :disabled="!canInput"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="时分"
              />
            </div>
            <div class="jiajian"><i class="el-icon-plus" @click="adddateline()"></i></div>
            <div class="jiajian"><i class="el-icon-minus" @click="deldateline(index)"></i></div>
          </el-form-item>
          <el-form-item v-if="nowChanceStau === 'add'" label="数据项选择:" prop="completionDate" class="w50p">
            <el-select v-model="dataitemmessage" :placeholder="formData.dataItemName" :disabled="!canInput" @change="adddataitem">
              <el-option
                v-for="(item,index) in dataItemList"
                :key="index"
                :label="item.dataItemName"
                :value="{value:item.dataItemId,name:item.dataItemName}"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据项展示:" prop="completionDate" class="w100p">
            <div style="border:1px solid #d9d9d9;width:100%;min-height:30px;display:flex;flex-wrap: wrap;">
              <div v-for="(item,index) in nowshowdataitemList" :key="index" class="dataitemsty" @click="deldataitem(index)">
                {{ item.dataItemName }}
                <i class="el-icon-minus"></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        :title="'查看'+'摄像头拍照配置'"
        :visible.sync="dialogFormsVisible"
        :before-close="() => {dialogFormsVisible = false}"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="采集名称:" prop="batchNo" class="w50p">
            <el-input v-model="formData.collectName" disabled />
          </el-form-item>
          <el-form-item label="采集设施:" prop="batchName" class="w50p">
            <el-select v-model="formData.facilityNo" :placeholder="formData.facilityName" disabled @change="selectfac">
              <el-option
                v-for="(item,index) in facilityList"
                :key="index"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集摄像头:" prop="batchName" class="w50p">
            <el-select v-model="cameramessage" :placeholder="formData.cameraName" disabled>
              <el-option
                v-for="(item,index) in cameraList"
                :key="index"
                :label="item.cameraName"
                :value="{value:item.cameraId,name:item.cameraName} "
              />
            </el-select>
          </el-form-item>
          <el-form-item label="执行选择:" prop="completionDate" class="w50p">
            <el-select v-model="formData.once" disabled>
              <el-option
                v-for="(item,index) in onceList"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集频率:" prop="completionDate" class="w100p">
            <div v-for="(item,index) in datelist" :key="index">
              <el-time-picker
                v-model="item.date"
                disabled
                format="HH:mm"
                value-format="HH:mm"
                placeholder="时分秒"
              />
            </div>
            <!-- <div class="jiajian"><i class="el-icon-plus" @click="adddateline()"></i></div>
            <div class="jiajian"><i class="el-icon-minus" @click="deldateline(index)"></i></div> -->
          </el-form-item>
          <el-form-item v-if="nowChanceStau === 'add'" label="数据项选择:" prop="completionDate" class="w50p">
            <el-select v-model="dataitemmessage" :placeholder="formData.dataItemName" disabled @change="adddataitem">
              <el-option
                v-for="(item,index) in dataItemList"
                :key="index"
                :label="item.dataItemName"
                :value="{value:item.dataItemId,name:item.dataItemName}"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据项展示:" prop="completionDate" class="w100p">
            <div style="border:1px solid #6ecae3;width:100%;min-height:30px;display:flex;flex-wrap: wrap;">
              <div v-for="(item,index) in nowshowdataitemList" :key="index" class="dataitemsty">
                {{ item.dataItemName }}
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogFormsVisible = false">
            关 闭
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/growth-record-management/camera-photo-configuration/index";
import nowpagereqtwo from "@/api/system-settings/environmental-data-test-record/index";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot"
import { mymixin } from "@/utils/mixin"
import { mapGetters } from 'vuex';
// import { getToken } from '@/utils/auth';
export default {
  name: "CameraPhotoConfiguration",
  components: { SearchForm, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '采集名称',
          prop: 'collectName',
          type: 'input',
        }
      ],
      searchlist: {},
      nowshowdataitemList: [],
      datelist: [
        { date: "" }
      ],
      onceList: [
        { name: '一次性', value: true },
        { name: '重复', value: false }
      ],
      cameramessage: {},
      cameraList: [],
      dataitemmessage: {},
      dataItemList: [],
      facilityList: [],
      // 一般为农业类型id
      farmingTypeNo: "",
      // 所搜索框内容
      searchList: {},
      dialogFormVisible: false,
      dialogFormsVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau(nezh) {
      if (nezh === 'edit') {
        this.nowshowdataitemList = []
      }
      this.cameramessage = {}
      this.dataitemmessage = {}
    }
  },
  created() {
  },
  mounted() {
    this.getselectdatalist()
    this.getTableDataList()
  },
  methods: {
    adddateline() {
      this.datelist.push({ date: "" })
    },
    deldateline(i) {
      this.datelist.splice(i, 1)
    },
    adddataitem(e) {
      let jk = { dataItemName: e.name,
        dataItemId: e.value }
      this.nowshowdataitemList.push(jk)
    },
    deldataitem(i) {
      this.nowshowdataitemList.splice(i, 1)
    },
    // 获取下拉框数据
    // 获取下拉框数据
    getselectdatalist() {
      this.getdataitems();
      let faciparams = {};
      faciparams = {
        organizationList: sessionStorage
          .getItem("organizationList")
          .split(","),
        farmingTypeNo: sessionStorage.getItem("farmingTypeNo")
      };
      // 获取地块
      nowpagereqtwo.getfacilityAll(faciparams).then(
        res => {
          this.facilityList = res.data
        }
      )
      // 获取地块
      nowpagereqtwo.getcameraAll().then(
        res => {
          this.cameraList = res.data;
        }
      )
    },
    // 获取数据项
    getdataitems() {
      nowpagereqtwo.getdataitems({}).then(
        res => {
          this.dataItemList = res.data
        }
      )
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      this.tableData = []
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
      };
      // if (this.searchList.collectName && this.searchList.collectName.length > 0) {
      //   nowpagereq.getlist(params, this.searchList.collectName).then(
      //     res => {
      //       if (res.code === 1) {
      //         // this.$message.success('查询成功')
      //       } else {
      //         this.$message.error('查询失败')
      //       }
      //       this.loading = false;
      //       let data = res.data;
      //       // 赋值总条数
      //       this.totalSize = data.length;
      //       // 赋值数组
      //       this.tableData = data;
      //       this.addblankmet()
      //       this.resetActionBar();
      //     }
      //   )
      //   return
      // }
      nowpagereq.getlist(params, this.searchList.collectName).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error('查询失败')
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.addblankmet()
        this.resetActionBar();
      });
      // 判断搜索输入框数据
    },
    search(searchList) {
      this.searchList = searchList
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    selectfac(e) {
      if (e) {
        let params = {
          facilityNo: e
        }
        nowpagereqtwo.getdataitems(params).then(
          res => {
            this.dataItemList = res.data
          }
        )
        nowpagereqtwo.getdataFacilityitems(params).then(
          res => {
            this.cameraList = res.data
          }
        )
      }
    },
    add() {
      this.getdataitems();
      this.addActive = false;
      this.formData = {};
      this.datelist = [];
      this.nowshowdataitemList = [];
      this.openDialog('add');
      this.canInput = true;
    },
    handleEdit(row) {
      if (row.indflag) {
        this.$message.warning("请勿选择空数据")
        return
      }
      nowpagereqtwo.getdataitems({}).then(
        res => {
          this.dataItemList = res.data
        }
      )
      this.cameramessage = {}
      this.formData = row;
      // let camera = this.cameraList.find(el => el.cameraId === row.cameraId);
      let camera = { ...row };
      this.formData.cameramessage = { value: camera.cameraId, name: camera.cameraName };
      nowpagereq.querybycondition(row.collectSettingNo).then(
        res => {
          this.nowshowdataitemList = res.data.dataItemIdList.map(
            itemone => {
              let obj = this.dataItemList.find(el => el.dataItemId === itemone)
              return {
                dataItemName: obj.dataItemName || '未获取到数据项名称'
              }
            }
          )
          this.datelist = []
          let newdata = res.data.collectSettingTimeList
          newdata.map(
            itemtwo => {
              this.datelist.push({ "date": `2021-10-10 ${itemtwo}` })
            }
          )
        }
      )
      // this.openDialog('edit');
      this.dialogFormsVisible = true
      this.canInput = false;
    },
    cancel() {
      this.addActive = true;
      this.closeDialog();
      this.formData = {};
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      let notvalue = true
      // console.log(list)
      this.nowSelectList = list.map(item => {
        if (item.collectSettingNo) {
          return item.collectSettingNo
        } else {
          notvalue = false
          return ""
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return
      }
      if (this.nowSelectList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 删除时触发方法
    delmessage() {
      nowpagereq.dellist(this.nowSelectList).then(
        res => {
          if (res.code === 1) {
            this.$message.success("删除成功！");
            this.getTableDataList();
          } else {
            this.$message.error("删除失败！");
          }
        }
      )
    },
    handleDelete(data) {
      // nowpagereq.dellist([data.collectSettingNo]).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success('删除成功')
      //     this.getTableDataList();
      //   } else {
      //     this.$message.error('删除失败')
      //   }
      // })
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          nowpagereq.dellist([data.collectSettingNo]).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    async save() {
      if (this.nowshowdataitemList === []) {
        this.$message.warning("请至少选择一个数据项")
        return
      }
      // -----保存状态判断-----
      if (this.nowChanceStau === 'edit') {
        let editparams = {
          ...this.formData
        }
        delete editparams.cameraName
        delete editparams.facilityName
        if (this.cameramessage.value) {
          editparams.cameraName = this.cameramessage.name
          editparams.cameraId = this.cameramessage.value
        }
        let zzznewlist = []
        this.nowshowdataitemList.map(
          ityone => {
            zzznewlist.push(
              { "collectSettingNo": editparams.collectSettingNo,
                ...ityone
              }
            )
          }
        )
        editparams.dataItemCollectBOList = zzznewlist
        editparams.collectRateSettingList = this.datelist.map(
          item => {
            // const dt = new Date(item.date);
            // const hh = dt.getHours();
            // const mm = dt.getMinutes();
            // const ss = dt.getSeconds();
            return item.date
          }
        )
        // editparams.dataItemCollectBOList = this.nowshowdataitemList
        nowpagereq.editlist(editparams).then(res => {
          if (res.code === 1) {
            this.$message.success("修改成功！");
            this.closeDialog();
            this.getTableDataList();
            this.getselectdatalist()
          } else {
            this.$message.error("修改失败！");
          }
        });
      } else if (this.nowChanceStau === 'add') {
        // 新增接口
        let addparams = {
          ...this.formData
        }
        if (this.cameramessage.value) {
          addparams.cameraName = this.cameramessage.name
          addparams.cameraId = this.cameramessage.value
        }
        if (addparams.facilityNo) {
          this.facilityList.forEach(
            item => {
              if (item.facilityNo === addparams.facilityNo) {
                addparams.organizationNo = item.organizationNo
              }
            }
          )
        }
        addparams.dataItemCollectBOList = this.nowshowdataitemList
        addparams.collectSettingTimeList = this.datelist.map(
          item => {
            // const dt = new Date(item.date);
            // const hh = dt.getHours();
            // const mm = dt.getMinutes();
            // const ss = dt.getSeconds();
            return item.date
          }
        )
        nowpagereq.addlist(addparams).then(res => {
          if (res.code === 1) {
            this.$message.success("添加成功！");
            this.closeDialog();
            this.getTableDataList();
            this.getselectdatalist()
          } else {
            this.$message.error("添加失败！");
          }
        });
      }
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === 'add' ? '新增' : '编辑'
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = '';
    }
  }
};
</script>

<style scoped lang="scss">
.jiajian{
  width: 30px;
  height: 30px;
  line-height: 30px;
  margin-left: 5px;
  border: aqua 1px solid;
  display: flex;
  justify-content: center;
  align-content: center;
  align-items: center;
}
.dataitemsty{
  min-width: 100px;
  height: 30px;
  line-height: 30px;
  margin: 5px;
  text-align: center;
  border: 1px solid #005267;
  white-space: nowrap;
  cursor: pointer;
}
</style>
